/*
Dijjer - A Peer to Peer HTTP Cache
Copyright (C) 2004,2005  Change.Tv, Inc

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

package dijjer.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
import dijjer.Dijjer;

public class Misc {

	public static final String VERSION = "$Id: Misc.java 2 2008-03-21 14:33:03Z ian.clarke $";

	private static final Random _random = new Random();

	public static int nextInt() {
		return _random.nextInt();
	}

	public static void startThread(Runnable runnable) {
		startThread(null, runnable);
	}

	public static void startThread(String name, Runnable runnable) {
		Thread t = new Thread(runnable);
		if (name != null) {
			t.setName(name);
		}
		t.start();
	}

	public static String bytes2Hex(byte[] b) {
		final String[] HEX_DIGITS = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c",
			"d", "e", "f"};
		StringBuffer sb = new StringBuffer(b.length * 2);
		for (int x = 0; x < b.length; x++) {
			int nb = b[x] & 0xFF;
			int i_1 = (nb >> 4) & 0xF;
			int i_2 = nb & 0xF;
			sb.append(HEX_DIGITS[i_1] + HEX_DIGITS[i_2]);
		}
		return sb.toString();
	}
	
	public static Random getRandom() {
		return _random;
	}
	
	public static HttpURLConnection openHttpUrlConnection(URL url) throws IOException {
		HttpURLConnection huc = (HttpURLConnection) url.openConnection();
		huc.setRequestProperty("User-Agent", "Dijjer/1.0b/build-" + Dijjer.BUILD);
        huc.setRequestProperty("Dijjer-Version", "" + Dijjer.BUILD);
		return huc;
	}
}
